import axios from 'axios'
import { getToken } from './method'
import { message } from 'ant-design-vue'

import { replaceHost, commonApiUploadImg } from 'nearby-common'
import { parser } from './const'

export let BASE_URL = 'https://oa.lianlianlvyou.com'

export const uploadImgUrl = BASE_URL + commonApiUploadImg().path

if (process.env.NODE_ENV !== 'production') {
  BASE_URL = 'http://192.167.246.37:31001'
  // BASE_URL = 'https://oa.lianlianlvyou.com'
}

let instance = axios.create({
  baseURL: BASE_URL,
  timeout: 60000,
  headers: { Authorization: getToken() }
})
instance.interceptors.request.use((config) => {
  if (!getToken()) {
    if (process.env.NODE_ENV !== 'production') {
      console.error('没有token')
    }
    return Promise.reject(new Error('用户失效'))
  }
  let reqUrl = config.url || ''
  const localHost = parser.getLocalHost(reqUrl)
  if (localHost) {
    reqUrl = replaceHost(reqUrl, localHost)
  }
  config.url = reqUrl
  return config
})
// 添加响应拦截器
instance.interceptors.response.use(
  (response) => {
    // 对响应数据做点什么
    if (!response.data) {
      return Promise.reject(new Error('processed'))
    }
    if (response.data.errMessage) {
      message.error(response.data.errMessage)
      return Promise.reject(new Error('processed'))
    } else {
      return response.data
    }
  },
  () => {
    // 对响应错误做点什么
    return Promise.reject(new Error('processed'))
  }
)
instance.interceptors.response.use((res) => {
  // 这里可以对响应做预处理
  if (res.data.code && res.data.code.toString() === '10001') {
    return Promise.reject(new Error('用户失效'))
  }
  return res
})

export const http = instance
